<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://erdangjiade.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: xiaojie <997031758@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 分类管理
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\Category;
use app\admin\model\Config;
use app\common\controller\AdminBase;
use think\Request;

class Categories extends AdminBase
{
    public function index(Request $request)
    {
        if($request->isAjax()){
            $bulider = Category::order('sort')
                ->where('type',$request->post('type'));
            return $this->layuiTableJson($bulider->count(),$bulider->select());
        }

        return view('index',[
            'config_group' => Config::where('key','category_type')->find(),
        ]);
    }

    public function create(Request $request)
    {
        return view('create',['type'=>$request->get('type')]);
    }

    public function apiGetCategory(Request $request, Category $category)
    {
        if($request->isAjax()){
            $first_category = [['id'=>0,'title'=>'作为一级分类','parent_id'=>0,'is_directory'=>0]];
            $categories = $category
                ->field('id,title,parent_id,is_directory')
                ->order('sort')
                ->where('parent_id',$request->get('parent_id/d'))
                ->where('type',$request->get('type'))
                ->select()->toArray();

            return $this->success('数据获取成功','',$request->get('parent_id/d')===0?array_merge($first_category,$categories):$categories);
        }
    }

    public function save(Request $request, Category $category)
    {
        $category->data($request->only(['parent_id','title','description','image','status','is_directory','type']));
        $category->save();

        return $this->success('添加成功','index');
    }

    public function edit(Request $request)
    {
        $category = Category::find($request->get('id'));

        return view('edit',[
            'category' => $category,
            'chooseData' => json_encode(explode('-',trim($category->path.$category->id,'-')))
        ]);
    }

    public function update(Request $request)
    {
        $category = Category::find($request->post('id/d'));
        $category->save($request->only(['parent_id','title','description','image','status','is_directory']));
        return $this->success('保存成功','index');
    }

    public function delete(Request $request)
    {
        Category::destroy($request->get('id'));

        return $this->success('保存成功','index');
    }

}
